package com.samtech.commons;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractMessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.LocaleResolver;

/**
 * Utils - Web
 * 
 */
public final class WebUtils {

	/**
	 * PoolingHttpClientConnectionManager
	 */
	private static final PoolingHttpClientConnectionManager HTTP_CLIENT_CONNECTION_MANAGER;

	/**
	 * CloseableHttpClient
	 */
	private static final CloseableHttpClient HTTP_CLIENT;

	static {
		HTTP_CLIENT_CONNECTION_MANAGER = new PoolingHttpClientConnectionManager(RegistryBuilder
				.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory())
				.register("https", SSLConnectionSocketFactory.getSocketFactory()).build());
		HTTP_CLIENT_CONNECTION_MANAGER.setDefaultMaxPerRoute(100);
		HTTP_CLIENT_CONNECTION_MANAGER.setMaxTotal(200);
		RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(60000).setConnectTimeout(60000)
				.setSocketTimeout(60000).build();
		HTTP_CLIENT = HttpClientBuilder.create().setConnectionManager(HTTP_CLIENT_CONNECTION_MANAGER)
				.setDefaultRequestConfig(requestConfig).build();
	}
	private static String configPropertiesBean = "configProperties";

	/**
	 * 不可实例化
	 */
	private WebUtils() {
	}

	/**
	 * 获取HttpServletRequest
	 * 
	 * @return HttpServletRequest
	 */
	public static HttpServletRequest getRequest() {
		RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
		return requestAttributes != null && requestAttributes instanceof ServletRequestAttributes
				? ((ServletRequestAttributes) requestAttributes).getRequest()
				: null;
	}

	/**
	 * 获取HttpServletResponse
	 * 
	 * @return HttpServletResponse
	 */
	public static HttpServletResponse getResponse() {
		RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
		return requestAttributes != null && requestAttributes instanceof ServletRequestAttributes
				? ((ServletRequestAttributes) requestAttributes).getResponse()
				: null;
	}

	/**
	 * 判断是否为AJAX请求
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @return 是否为AJAX请求
	 */
	public static boolean isAjaxRequest(HttpServletRequest request) {
		Assert.notNull(request);

		return StringUtils.equalsIgnoreCase(request.getHeader("X-Requested-With"), "XMLHttpRequest");
	}

	/**
	 * 添加cookie
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @param response
	 *            HttpServletResponse
	 * @param name
	 *            Cookie名称
	 * @param value
	 *            Cookie值
	 * @param maxAge
	 *            有效期(单位: 秒)
	 * @param path
	 *            路径
	 * @param domain
	 *            域
	 * @param secure
	 *            是否启用加密
	 */
	public static void addCookie(HttpServletRequest request, HttpServletResponse response, String name, String value,
			Integer maxAge, String path, String domain, Boolean secure) {
		Assert.notNull(request);
		Assert.notNull(response);
		Assert.hasText(name);
		Assert.hasText(value);

		try {
			name = URLEncoder.encode(name, "UTF-8");
			value = URLEncoder.encode(value, "UTF-8");
			Cookie cookie = new Cookie(name, value);
			if (maxAge != null) {
				cookie.setMaxAge(maxAge);
			}
			if (StringUtils.isNotEmpty(path)) {
				cookie.setPath(path);
			}
			if (StringUtils.isNotEmpty(domain)) {
				cookie.setDomain(domain);
			}
			if (secure != null) {
				cookie.setSecure(secure);
			}
			response.addCookie(cookie);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	/**
	 * 添加cookie
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @param response
	 *            HttpServletResponse
	 * @param name
	 *            Cookie名称
	 * @param value
	 *            Cookie值
	 * @param maxAge
	 *            有效期(单位: 秒)
	 */
	public static void addCookie(HttpServletRequest request, HttpServletResponse response, String name, String value,
			Integer maxAge) {
		Assert.notNull(request);
		Assert.notNull(response);
		Assert.hasText(name);
		Assert.hasText(value);

		Setting setting = SystemSettingUtils.getSetting();
		String cookiePath = setting.getCookiePath();
		String cookieDomain = setting.getCookieDomain();

		addCookie(request, response, name, value, maxAge, cookiePath, cookieDomain, null);
	}

	/**
	 * 添加cookie
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @param response
	 *            HttpServletResponse
	 * @param name
	 *            Cookie名称
	 * @param value
	 *            Cookie值
	 */
	public static void addCookie(HttpServletRequest request, HttpServletResponse response, String name, String value) {
		Assert.notNull(request);
		Assert.notNull(response);
		Assert.hasText(name);
		Assert.hasText(value);

		Setting setting = SystemSettingUtils.getSetting();
		String cookiePath = setting.getCookiePath();
		String cookieDomain = setting.getCookieDomain();
		addCookie(request, response, name, value, null, cookiePath, cookieDomain, null);
	}

	/**
	 * 获取cookie
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @param name
	 *            Cookie名称
	 * @return Cookie值，若不存在则返回null
	 */
	public static String getCookie(HttpServletRequest request, String name) {
		Assert.notNull(request);
		Assert.hasText(name);

		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			try {
				name = URLEncoder.encode(name, "UTF-8");
				for (Cookie cookie : cookies) {
					if (name.equals(cookie.getName())) {
						return URLDecoder.decode(cookie.getValue(), "UTF-8");
					}
				}
			} catch (UnsupportedEncodingException e) {
				throw new RuntimeException(e.getMessage(), e);
			}
		}
		return null;
	}

	/**
	 * 移除cookie
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @param response
	 *            HttpServletResponse
	 * @param name
	 *            Cookie名称
	 * @param path
	 *            路径
	 * @param domain
	 *            域
	 */
	public static void removeCookie(HttpServletRequest request, HttpServletResponse response, String name, String path,
			String domain) {
		Assert.notNull(request);
		Assert.notNull(response);
		Assert.hasText(name);

		try {
			name = URLEncoder.encode(name, "UTF-8");
			Cookie cookie = new Cookie(name, null);
			cookie.setMaxAge(0);
			if (StringUtils.isNotEmpty(path)) {
				cookie.setPath(path);
			}
			if (StringUtils.isNotEmpty(domain)) {
				cookie.setDomain(domain);
			}
			response.addCookie(cookie);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	/**
	 * 移除cookie
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @param response
	 *            HttpServletResponse
	 * @param name
	 *            Cookie名称
	 */
	public static void removeCookie(HttpServletRequest request, HttpServletResponse response, String name) {
		Assert.notNull(request);
		Assert.notNull(response);
		Assert.hasText(name);

		Setting setting = SystemSettingUtils.getSetting();
		String cookiePath = setting.getCookiePath();
		String cookieDomain = setting.getCookieDomain();
		removeCookie(request, response, name, cookiePath, cookieDomain);
	}

	/**
	 * 参数解析
	 * 
	 * @param query
	 *            查询字符串
	 * @param encoding
	 *            编码格式
	 * @return 参数
	 */
	public static Map<String, String> parse(String query, String encoding) {
		Assert.hasText(query);

		Charset charset;
		if (StringUtils.isNotEmpty(encoding)) {
			charset = Charset.forName(encoding);
		} else {
			charset = Charset.forName("UTF-8");
		}
		List<NameValuePair> nameValuePairs = URLEncodedUtils.parse(query, charset);
		Map<String, String> parameterMap = new HashMap<>();
		for (NameValuePair nameValuePair : nameValuePairs) {
			parameterMap.put(nameValuePair.getName(), nameValuePair.getValue());
		}
		return parameterMap;
	}

	/**
	 * 解析参数
	 * 
	 * @param query
	 *            查询字符串
	 * @return 参数
	 */
	public static Map<String, String> parse(String query) {
		Assert.hasText(query);

		return parse(query, null);
	}

	/**
	 * 重定向
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @param response
	 *            HttpServletResponse
	 * @param url
	 *            URL
	 * @param contextRelative
	 *            是否相对上下文路径
	 * @param http10Compatible
	 *            是否兼容HTTP1.0
	 */
	public static void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url,
			boolean contextRelative, boolean http10Compatible) {
		Assert.notNull(request);
		Assert.notNull(response);
		Assert.hasText(url);

		StringBuilder targetUrl = new StringBuilder();
		if (contextRelative && url.startsWith("/")) {
			targetUrl.append(request.getContextPath());
		}
		targetUrl.append(url);
		String encodedRedirectURL = response.encodeRedirectURL(targetUrl.toString());
		if (http10Compatible) {
			try {
				response.sendRedirect(encodedRedirectURL);
			} catch (IOException e) {
				throw new RuntimeException(e.getMessage(), e);
			}
		} else {
			response.setStatus(303);
			response.setHeader("Location", encodedRedirectURL);
		}
	}

	/**
	 * 重定向
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @param response
	 *            HttpServletResponse
	 * @param url
	 *            URL
	 */
	public static void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) {
		sendRedirect(request, response, url, true, true);
	}

	/**
	 * POST请求
	 * 
	 * @param url
	 *            URL
	 * @param parameterMap
	 *            请求参数
	 * @return 返回结果
	 */
	public static String post(String url, Map<String, Object> parameterMap) {
		Assert.hasText(url);

		String result = null;
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<>();
			if (parameterMap != null) {
				for (Map.Entry<String, Object> entry : parameterMap.entrySet()) {
					String name = entry.getKey();
					String value = ConvertUtils.convert(entry.getValue());
					if (StringUtils.isNotEmpty(name)) {
						nameValuePairs.add(new BasicNameValuePair(name, value));
					}
				}
			}
			HttpPost httpPost = new HttpPost(url);
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
			CloseableHttpResponse httpResponse = HTTP_CLIENT.execute(httpPost);
			try {
				HttpEntity httpEntity = httpResponse.getEntity();
				if (httpEntity != null) {
					result = EntityUtils.toString(httpEntity);
					EntityUtils.consume(httpEntity);
				}
			} finally {
				try {
					httpResponse.close();
				} catch (IOException e) {
				}
			}
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e.getMessage(), e);
		} catch (ClientProtocolException e) {
			throw new RuntimeException(e.getMessage(), e);
		} catch (ParseException e) {
			throw new RuntimeException(e.getMessage(), e);
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
		return result;
	}

	/**
	 * GET请求
	 * 
	 * @param url
	 *            URL
	 * @param parameterMap
	 *            请求参数
	 * @return 返回结果
	 */
	public static String get(String url, Map<String, Object> parameterMap) {
		Assert.hasText(url);

		String result = null;
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<>();
			if (parameterMap != null) {
				for (Map.Entry<String, Object> entry : parameterMap.entrySet()) {
					String name = entry.getKey();
					String value = ConvertUtils.convert(entry.getValue());
					if (StringUtils.isNotEmpty(name)) {
						nameValuePairs.add(new BasicNameValuePair(name, value));
					}
				}
			}
			HttpGet httpGet = new HttpGet(url + (StringUtils.contains(url, "?") ? "&" : "?")
					+ EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")));
			CloseableHttpResponse httpResponse = HTTP_CLIENT.execute(httpGet);
			try {
				HttpEntity httpEntity = httpResponse.getEntity();
				if (httpEntity != null) {
					result = EntityUtils.toString(httpEntity);
					EntityUtils.consume(httpEntity);
				}
			} finally {
				try {
					httpResponse.close();
				} catch (IOException e) {
				}
			}
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e.getMessage(), e);
		} catch (ParseException e) {
			throw new RuntimeException(e.getMessage(), e);
		} catch (ClientProtocolException e) {
			throw new RuntimeException(e.getMessage(), e);
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
		return result;
	}

	/**
	 * POST请求
	 * 
	 * @param url
	 *            URL
	 * @param xml
	 *            XML
	 * @return 返回结果
	 */
	public static String post(String url, String xml) {
		Assert.hasText(url);

		String result = null;
		try {
			HttpPost httpPost = new HttpPost(url);
			httpPost.setEntity(new StringEntity(xml, "UTF-8"));
			CloseableHttpResponse httpResponse = HTTP_CLIENT.execute(httpPost);
			try {
				HttpEntity httpEntity = httpResponse.getEntity();
				if (httpEntity != null) {
					result = EntityUtils.toString(httpEntity, "UTF-8");
					EntityUtils.consume(httpEntity);
				}
			} finally {
				try {
					httpResponse.close();
				} catch (IOException e) {
				}
			}
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e.getMessage(), e);
		} catch (ClientProtocolException e) {
			throw new RuntimeException(e.getMessage(), e);
		} catch (ParseException e) {
			throw new RuntimeException(e.getMessage(), e);
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
		return result;
	}

	// status

	/**
	 * 默认200状态消息
	 */
	public static final String DEFAULT_OK_MESSAGE = "common.message.ok";

	/**
	 * 默认400状态消息
	 */
	public static final String DEFAULT_BAD_REQUEST_MESSAGE = "common.message.badRequest";

	/**
	 * 默认401状态消息
	 */
	public static final String DEFAULT_UNAUTHORIZED_MESSAGE = "common.message.unauthorized";

	/**
	 * 默认403状态消息
	 */
	public static final String DEFAULT_FORBIDDEN_MESSAGE = "common.message.forbidden";

	/**
	 * 默认404状态消息
	 */
	public static final String DEFAULT_NOT_FOUND_MESSAGE = "common.message.notFound";

	/**
	 * 默认422状态消息
	 */
	public static final String DEFAULT_UNPROCESSABLE_ENTITY_MESSAGE = "common.message.unprocessableEntity";

	/**
	 * 200状态ResponseEntity
	 */
	public static ResponseEntity<Map<String, String>> OK = null;

	/**
	 * 400状态ResponseEntity
	 */
	public static ResponseEntity<Map<String, String>> BAD_REQUEST = null;

	/**
	 * 401状态ResponseEntity
	 */
	public static ResponseEntity<Map<String, String>> UNAUTHORIZED = null;

	/**
	 * 403状态ResponseEntity
	 */
	public static ResponseEntity<Map<String, String>> FORBIDDEN = null;

	/**
	 * 404状态ResponseEntity
	 */
	public static ResponseEntity<Map<String, String>> NOT_FOUND = null;

	/**
	 * 422状态ResponseEntity
	 */
	public static ResponseEntity<Map<String, String>> UNPROCESSABLE_ENTITY = null;

	/**
	 * JSON内容类型
	 */
	private static final String JSON_CONTENT_TYPE = "application/json";

	/**
	 * 消息KEY
	 */
	private static final String MESSAGE_KEY = "message";

	/**
	 * 设置状态
	 * 
	 * @param response
	 *            HttpServletResponse
	 * @param httpStatus
	 *            HttpStatus
	 * @param data
	 *            数据
	 */
	public static void status(HttpServletResponse response, HttpStatus httpStatus, Object data) {
		Assert.notNull(response);
		Assert.notNull(httpStatus);
		Assert.notNull(data);

		response.setContentType(JSON_CONTENT_TYPE);
		response.setStatus(httpStatus.value());
		try {
			JsonUtils.writeValue(response.getWriter(), data);
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	/**
	 * 设置状态
	 * 
	 * @param response
	 *            HttpServletResponse
	 * @param httpStatus
	 *            HttpStatus
	 * @param message
	 *            消息
	 * @param args
	 *            参数
	 */
	public static void status(HttpServletResponse response, HttpStatus httpStatus, String message, Object... args) {
		Assert.notNull(response);
		Assert.notNull(httpStatus);
		Assert.hasText(message);

		Map<String, String> data = new HashMap<>();
		data.put(MESSAGE_KEY, getMessage(message, args));
		status(response, httpStatus, data);
	}

	/**
	 * 返回状态ResponseEntity
	 * 
	 * @param httpStatus
	 *            HttpStatus
	 * @param data
	 *            数据
	 * @return ResponseEntity
	 */
	public static <T> ResponseEntity<T> status(HttpStatus httpStatus, T data) {
		Assert.notNull(httpStatus);
		Assert.notNull(data);

		return new ResponseEntity<>(data, httpStatus);
	}

	/**
	 * 返回状态ResponseEntity
	 * 
	 * @param httpStatus
	 *            HttpStatus
	 * @param message
	 *            消息
	 * @param args
	 *            参数
	 * @return ResponseEntity
	 */
	public static ResponseEntity<Map<String, String>> status(HttpStatus httpStatus, String message, Object... args) {
		Assert.notNull(httpStatus);
		Assert.hasText(message);

		Map<String, String> data = new HashMap<>();
		data.put(MESSAGE_KEY, getMessage(message, args));
		return status(httpStatus, data);
	}

	/**
	 * 设置200状态
	 * 
	 * @param response
	 *            HttpServletResponse
	 * @param message
	 *            消息
	 * @param args
	 *            参数
	 */
	public static void ok(HttpServletResponse response, String message, Object... args) {
		status(response, HttpStatus.OK, message, args);
	}

	/**
	 * 设置400状态
	 * 
	 * @param response
	 *            HttpServletResponse
	 * @param message
	 *            消息
	 * @param args
	 *            参数
	 */
	public static void badRequest(HttpServletResponse response, String message, Object... args) {
		status(response, HttpStatus.BAD_REQUEST, message, args);
	}

	/**
	 * 设置401状态
	 * 
	 * @param response
	 *            HttpServletResponse
	 * @param message
	 *            消息
	 * @param args
	 *            参数
	 */
	public static void unauthorized(HttpServletResponse response, String message, Object... args) {
		status(response, HttpStatus.UNAUTHORIZED, message, args);
	}

	/**
	 * 设置403状态
	 * 
	 * @param response
	 *            HttpServletResponse
	 * @param message
	 *            消息
	 * @param args
	 *            参数
	 */
	public static void forbidden(HttpServletResponse response, String message, Object... args) {
		status(response, HttpStatus.FORBIDDEN, message, args);
	}

	/**
	 * 设置404状态
	 * 
	 * @param response
	 *            HttpServletResponse
	 * @param message
	 *            消息
	 * @param args
	 *            参数
	 */
	public static void notFound(HttpServletResponse response, String message, Object... args) {
		status(response, HttpStatus.NOT_FOUND, message, args);
	}

	/**
	 * 设置422状态
	 * 
	 * @param response
	 *            HttpServletResponse
	 * @param message
	 *            消息
	 * @param args
	 *            参数
	 */
	public static void unprocessableEntity(HttpServletResponse response, String message, Object... args) {
		status(response, HttpStatus.UNPROCESSABLE_ENTITY, message, args);
	}

	/**
	 * 返回200状态ResponseEntity
	 * 
	 * @param message
	 *            消息
	 * @param args
	 *            参数
	 * @return 200状态ResponseEntity
	 */
	public static ResponseEntity<Map<String, String>> ok(String message, Object... args) {
		return status(HttpStatus.OK, message, args);
	}

	/**
	 * 返回400状态ResponseEntity
	 * 
	 * @param message
	 *            消息
	 * @param args
	 *            参数
	 * @return 400状态ResponseEntity
	 */
	public static ResponseEntity<Map<String, String>> badRequest(String message, Object... args) {
		return status(HttpStatus.BAD_REQUEST, message, args);
	}

	/**
	 * 返回401状态ResponseEntity
	 * 
	 * @param message
	 *            消息
	 * @param args
	 *            参数
	 * @return 401状态ResponseEntity
	 */
	public static ResponseEntity<Map<String, String>> unauthorized(String message, Object... args) {
		return status(HttpStatus.UNAUTHORIZED, message, args);
	}

	/**
	 * 返回403状态ResponseEntity
	 * 
	 * @param message
	 *            消息
	 * @param args
	 *            参数
	 * @return 403状态ResponseEntity
	 */
	public static ResponseEntity<Map<String, String>> forbidden(String message, Object... args) {
		return status(HttpStatus.FORBIDDEN, message, args);
	}

	/**
	 * 返回404状态ResponseEntity
	 * 
	 * @param message
	 *            消息
	 * @param args
	 *            参数
	 * @return 404状态ResponseEntity
	 */
	public static ResponseEntity<Map<String, String>> notFound(String message, Object... args) {
		return status(HttpStatus.NOT_FOUND, message, args);
	}

	/**
	 * 返回422状态ResponseEntity
	 * 
	 * @param message
	 *            消息
	 * @param args
	 *            参数
	 * @return 422状态ResponseEntity
	 */
	public static ResponseEntity<Map<String, String>> unprocessableEntity(String message, Object... args) {
		return status(HttpStatus.UNPROCESSABLE_ENTITY, message, args);
	}

	/**
	 * invoke inner web 获取国际化消息
	 * 
	 * @param code
	 *            代码
	 * @param args
	 *            参数
	 * @return 国际化消息
	 */
	public static String getMessage(String code, Object... args) {
		Assert.hasText(code);
		Locale locale = null;
		/*LocaleResolver localeResolver = getBean("localeResolver", LocaleResolver.class);
		locale = localeResolver.resolveLocale(null);*/
		//resourceMessageSource
		if(applicationContext==null) {
			return code;
		}
		AbstractMessageSource bean = applicationContext.getBean(AbstractMessageSource.class);
		return bean.getMessage(code, args, locale);
	}

	/**
	 * invoke inner web
	 * 
	 * @param propKey
	 * @return
	 */
	public static String getConfigPropertiesVal(String propKey) {
		if (propKey == null || propKey.trim().length() == 0)
			return null;
		Properties bean = getBean(configPropertiesBean, Properties.class);
		if (bean != null && bean.containsKey(propKey)) {
			return bean.getProperty(propKey);
		}
		return null;
	}

	/**
	 * 获取实例
	 * 
	 * @param name
	 *            Bean名称
	 * @return 实例
	 */
	protected static Object getBean(String name) {
		Assert.hasText(name);

		return applicationContext.getBean(name);
	}

	protected static <T> T getBean(String name, Class<T> type) {
		Assert.hasText(name);
		Assert.notNull(type);

		return applicationContext.getBean(name, type);
	}

	public static void setApplicationContext(ApplicationContext applicationContext) {
		WebUtils.applicationContext = applicationContext;
		initEntitys();
	}

	private static void initEntitys() {
		OK = ok(DEFAULT_OK_MESSAGE);
		BAD_REQUEST = badRequest(DEFAULT_BAD_REQUEST_MESSAGE);
		UNAUTHORIZED = unauthorized(DEFAULT_UNAUTHORIZED_MESSAGE);
		FORBIDDEN = forbidden(DEFAULT_FORBIDDEN_MESSAGE);
		NOT_FOUND = notFound(DEFAULT_NOT_FOUND_MESSAGE);
		UNPROCESSABLE_ENTITY = unprocessableEntity(DEFAULT_UNPROCESSABLE_ENTITY_MESSAGE);
	}

	private static ApplicationContext applicationContext;
}